package com.zxmseed.generatearticle.run;

import com.zxmseed.generatearticle.bo.GenerateProperties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

@Component
public class GenerateRun implements ApplicationRunner {

    @Autowired
    private GenerateProperties prop;

    // 判断末尾是否有标点符号
    private static Pattern patPunc = Pattern.compile("[`~!@#$^&*()=|{}':;',\\[\\]./?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]$");


    @Override
    public void run(ApplicationArguments args) throws Exception {


        String sourcePath = prop.getSourcePath();
        String targetPath = prop.getTargetPath();

        System.out.println("<<<<<<<<<<<<<<<<<<<<<程序开始>>>>>>>>>>>>>>>>>>>");

        // 检查源文件
        File sourceDirectory = new File(sourcePath);
        if (!sourceDirectory.exists()) {
            throw new Exception("源文件目录不存在，请检查");
        }

        // 检查源文件夹下文件是否存在
        File[] sourceFiles = sourceDirectory.listFiles();
        if (sourceFiles == null) {
            throw new Exception("源文件目录下未发现文件，请检查");
        }

        for (File sourceFile : sourceFiles) {
            if (!sourceFile.getName().endsWith("txt")) {
                throw new Exception("源文件只能是txt格式");
            }
        }

        // 检查目标文件
        File targetDirectory = new File(targetPath);
        if (!sourceDirectory.exists()) {
            throw new Exception("目标文件目录不存在，请检查");
        }

        File[] targetFiles = targetDirectory.listFiles();
        if (targetFiles == null || targetFiles.length != 1) {
            throw new Exception("目标文件目录下只能有一个文件，请检查");
        }

        if (!targetFiles[0].getName().endsWith("txt")) {
            throw new Exception("目标文件只能是txt格式");
        }

        String symbol = prop.getSymbol();
        System.out.println("开始按符号[" + symbol + "]分段处理文件");

        int index = 0;
        boolean first = true;
        String targets = FileUtils.readFileToString(targetFiles[0], prop.getCode());

        for (File sourceFile : sourceFiles) {
            List<String> outputSource = new ArrayList<>();
            List<String> sources = FileUtils.readLines(sourceFile, prop.getCode());

            String[] symbols = symbol.split("\\|");
            Random random = new Random();
            String[] targetSplits = targets.split(symbol);
            int end = 0;
            StringBuilder builder = new StringBuilder();

            for (String source : sources) {
                String[] sourceSplits = source.split(symbol);
            /*if (sourceSplits.length == 1) {
                builder.append(source);
                continue;
            }*/
                for (String segment : sourceSplits) {
                    if (StringUtils.isBlank(segment)) {
                        builder.append(segment);
                        continue;
                    }
                    String upSegment = StringUtils.trim(segment.toUpperCase());
                    if ("<P>".equals(upSegment) || (upSegment.startsWith("<P") && upSegment.endsWith(">")) || upSegment.endsWith("</P>")) {
                        builder.append(segment);
                        continue;
                    }
                    if (index > (targetSplits.length - 1)) {
                        index = 0;
                    }
                    // 排除空字符串
                    while (StringUtils.isBlank(targetSplits[index])) {
                        index++;
                        if (index > (targetSplits.length - 1)) {
                            index = 0;
                        }
                    }
                    int n = random.nextInt(symbols.length);
                    int symbIdx = source.indexOf(segment);
                    String inSymbol = patPunc.matcher(segment).find() || source.length() == segment.length() ? "" : "。";
                    if ((segment.length() + symbIdx) != source.length()) {
                        inSymbol = source.substring(segment.length() + symbIdx, segment.length() + symbIdx + 1);
                    }
                    String inSegment = targetSplits[index];

                    if ((end + inSegment.length()) > targets.length()) {
                        end = 0;
                    }
                    end += inSegment.length();

                    String inEndSymbol = symbols[n];
                    try {
                        inEndSymbol = targets.substring(end, end + 1);
                    } catch (Exception e) {

                    }
                    end += inEndSymbol.length();
                    builder.append(segment + inSymbol + inSegment + inEndSymbol);
                    index++;
                }
                outputSource.add(builder.toString());
                builder.delete(0, builder.length());
            }

            System.out.println("处理 [" + sourceFile.getName() + " ]完成");

            if (first) {
                // 创建生成目录
                System.out.println("删除生成目录");
                FileUtils.deleteDirectory(new File(prop.getOutputPath()));

                System.out.println("创建生成目录");
                FileUtils.forceMkdir(new File(prop.getOutputPath()));

                first = false;
            }

            File outputFile = new File(prop.getOutputPath() + File.separator + sourceFile.getName());
            FileUtils.writeLines(outputFile, outputSource);
        }


        System.out.println("<<<<<<<<<<<<<<<<<<<<<程序结束>>>>>>>>>>>>>>>>>>>");
        Runtime.getRuntime().exec("cmd /c start " + prop.getOutputPath());
    }

}
